using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Taxonomy.ContentTypeSync;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.SharePoint.Administration;

namespace MS.InformationManagement.ContentHub.ObjectDef.Features.Contenttypes_Upgdate
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("ed8ade64-a597-4dbc-9878-53f317c76f6b")]
    public class Contenttypes_UpgdateEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            SPSite siteCtHub = properties.Feature.Parent  as SPSite;                            
            SPWeb webCtHub = siteCtHub.RootWeb;
            
            if (ContentTypePublisher.IsContentTypeSharingEnabled(siteCtHub))
            { 
                ContentTypePublisher ctPublisher = new ContentTypePublisher(siteCtHub);
                IEnumerable<SPContentType> spContentTypes = webCtHub.AvailableContentTypes.Cast<SPContentType>().Where(ct => ct.Group == "MS Information Management");

                foreach (SPContentType spContentType in spContentTypes)
                {
                    if(!ctPublisher.IsPublished(spContentType)) 
                        ctPublisher.Publish(spContentType);
                    Thread.Sleep(100);
                }
            }
            
            SPWebApplication spWebApp = siteCtHub.WebApplication;
            SPService saMMS = spWebApp.Farm.Services.Cast<SPService>().FirstOrDefault(s => s.GetType().Name == "MetadataWebService");
            if(saMMS == null)
                throw new Exception("Es null");
            SPJobDefinition ctHubTimerJob = null;
            
            //Run the Content Type Hub Job
            //This timer job is associated with the MMS service application    
            ctHubTimerJob = saMMS.JobDefinitions.Cast<SPJobDefinition>().FirstOrDefault(jd => jd.Title == "Content Type Hub");

            if (ctHubTimerJob == null)
            {
                saMMS = spWebApp.Farm.Services.Cast<SPService>().FirstOrDefault(s => s.TypeName == "Microsoft SharePoint Foundation Timer");
                ctHubTimerJob = saMMS.JobDefinitions.Cast<SPJobDefinition>().FirstOrDefault(jd => jd.Title == "Content Type Hub");
            }

            DateTime startTime = DateTime.Now.ToUniversalTime();
            ctHubTimerJob.RunNow();

            while ((from SPJobHistory j in saMMS.JobHistoryEntries
                    where j.JobDefinitionId ==
                        ctHubTimerJob.Id && j.StartTime >
                        startTime
                    select j).Any() == false)
            {
                Thread.Sleep(100);
            }

            //Run the Content Type Subscriber Job
            //This timer job is associated with the subscriber's web application
            SPJobDefinition ctHubSubTimerJob = spWebApp.JobDefinitions.Cast<SPJobDefinition>().FirstOrDefault(jd => jd.Title == "Content Type Subscriber");
            startTime = new DateTime();
            startTime = DateTime.Now.ToUniversalTime();
            ctHubSubTimerJob.RunNow();

            while ((from SPJobHistory j in spWebApp.JobHistoryEntries
                    where j.JobDefinitionId ==
                        ctHubSubTimerJob.Id && j.StartTime >
                        startTime
                    select j).Any() == false)
            {
                Thread.Sleep(100);
            }              
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
